<?php
require_once("includes/public.inc.php");
if (!isset($_GET['code'])){
$uwxcode=$_GET['uwxcode'];
$locaurl=urlencode(WEBNAME."open.php?uwxcode=12");//网址解析
$urls="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx934cb7f852f6c585&redirect_uri=".$locaurl."&response_type=code&scope=snsapi_base#wechat_redirect";
//echo $urls;exit;
header("Location:".$urls);exit;
}
//启用session
//session_start();
//编码
header("Content-type: text/html; charset=utf-8");
//保存微信openid
$weixin_openid = "";
//保存从微信得到的code
$code = "";
//获得菜单中设置的state值
$state = "";
echo $_GET['code'];exit;

//修改为注册的测试号信息
$appid = "wx934cb7f852f6c585";
$secret = "94ea78cbbbd72c8a0ecbfc965a497afc";

if (isset($_GET['code'])){
	$weixin_openid = GetOpenid($_GET['code']);
	$code = $_GET['code'];
    //echo $resultStr;
}else{
    echo "NO CODE";
	return ;
}

// store session data
$_SESSION['weixin_openid']=$weixin_openid;

if($state == ""){
	//我的课堂
	echo $weixin_openid;exit;
}else if($state == "s2"){
	//订单记录
	header('Location: orderList.php');
}else{
	$textTpl="由认证接口进入我的课堂,<br/>您的 wx_openid: %s <br/> code: %s <br/> state: %s <br/>
	<a href='orderList.php'>订单记录</a>";
	$resultStr = sprintf($textTpl, $weixin_openid, $code, $state);

	echo  $resultStr ;
}



//获取微信的openid
function GetOpenid($c_code)
{
	$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid . "&secret=" . $secret . "&code=" . $c_code .  "&grant_type=authorization_code";
	//$url = "http://www.baidu.com";
	$result = getData($url);

	$jsondecode = json_decode($result);
	if($jsondecode != null){
		if(property_exists ( $jsondecode, "openid" ) )
		{
			return $jsondecode->{"openid"};
		}else{
			return "code is invalid.";
		}
	}

	return null;
}
//获取https的get请求结果
function getData($c_url)
{
	$curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $c_url); // 要访问的地址
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
//    curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
//    curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
    curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
    $tmpInfo = curl_exec($curl); // 执行操作
    if (curl_errno($curl)) {
       echo 'Errno'.curl_error($curl);//捕抓异常
    }
    curl_close($curl); // 关闭CURL会话
    return $tmpInfo; // 返回数据
}

?>